var restify = require('restify');
var jwtAuth = require('restify-jwt-auth-next');
var errs = require('restify-errors');
var jwt = require('jsonwebtoken');
var myconfig = require('./config');
global.isDev = process.env.NODE_ENV === "development";
global.config = global.isDev ? myconfig.dev : myconfig.pro;

var server = restify.createServer();

server.get(/\/public\/?.*/, restify.plugins.serveStatic({
    directory: __dirname
}));


var jwtoptions = {
  secret: config.secret,
  whitelist: ['/login','/refreshToken','/register','/active'],
  handler: function(req, res, next) {
    var token = req.query.jwt;
    jwt.verify(token, jwtoptions.secret, function(err, decoded) {
      if (err) {
        next(new errs.UnauthorizedError('not allow'));
      } else {
        req['decoded'] = decoded;
        return next();
      }
    });
  }
};

server.use(restify.plugins.queryParser());
server.use(restify.plugins.bodyParser());
server.use(jwtAuth(jwtoptions))

var diary = require('./apis/diary');
var user = require('./apis/user');
var login = require('./apis/login');
var register = require('./apis/register');
var comment = require('./apis/comment');
var images = require('./apis/images');
var notebook = require('./apis/notebook');

server.post('/login', login.login);
server.post('/register', register.register);
server.get('/refreshToken', login.refreshToken);
server.get('/active', register.active);

server.get('/diary/my', diary.my);
server.get('/diary/goods', diary.goods);
server.get('/diary/followers', diary.followers);
server.post('/diary/remove', diary.remove);
server.post('/diary/save', diary.save);

server.post('/images/upload', images.upload);

server.get('/comment/get', comment.get);
server.post('/comment/save', comment.save);
server.post('/comment/remove', comment.remove);

server.get('/user/all', user.all);
server.get('/user/info', user.info);
server.post('/user/update', user.update);

server.get('/notebook/get', notebook.get);
server.listen(config.port,config.host,function() {
  console.log('%s listening at %s', server.name, server.url);
});
